package talking.thread;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashSet;
import java.util.LinkedList;

/**
 * 接收消息，线程
 * @create 2020.5.21
 * @author Administrator
 */
public class ReceiveNews extends Thread{

	//保存消息
	private LinkedList<String> queue = new LinkedList();
	
	//服务器Socket
	private ServerSocket server;
	
	//客户端Socket
	private Socket socket;
	
	//保存Socket
	HashSet<Socket> socketSet = new HashSet<>();
	
	public ReceiveNews(ServerSocket server) {
		this.server = server;
	}
	
	@Override
	public void run(){
		
		while(true){
			//接收消息
			try {
				socket = server.accept();
				socketSet.add(socket);
				new Receive(socket).start();
			} catch (IOException e) {
				e.printStackTrace();
			}
		
		}
		
	}
	
	class Receive extends Thread {
		
		//接收消息
		private DataInputStream in;
		
		//Socket对象
		private Socket socket;
		
		public Receive(Socket socket){
			this.socket = socket;
			try {
				in = new DataInputStream(socket.getInputStream());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		@Override
		public void run(){
			while(true){
				String temp = "";
//				System.out.println("开始接收 ");
				try {
					temp = in.readUTF();
				} catch (IOException e) {
					e.printStackTrace();
				}
//				System.out.println("接收结束");
//				System.out.println(temp + " -----");
				//加入消息队列
				queue.add(temp);
				
				//将队列同步到发送消息线程
				new SendNews(queue,socketSet).start();
				
			}
		}
	}
}
